<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class City extends Model
{
    use HasFactory;

    public $guarded = [];

    public $timestamps = false;

    static function city($pid = 0) {
        return self::where('pid', $pid)->get();
    }

    static function city2($pid = 0) {
        return self::where('pid', $pid)->select("id as value", "name as label", 'full_name')->get();
    }

    // 三级城市 如[{label: '上海', children: '[]}]
    static function create_city_json($file) {
        $province = self::city2(0);
        foreach ($province as $p) {
            $cities = self::city2($p->value);
            foreach($cities as $city) {
                $regions = self::city2($city->value);
                $city->children = $regions;
                echo $city->label."\n";
            }
            $p->children = $cities;
        }
        file_put_contents($file, json_encode($province, JSON_UNESCAPED_SLASHES));
    }

    // 只有三级区域 [{},{},{}]
    static function create_region_json($file) {
        $provinces = self::city2(0);
        $data = [];
        foreach($provinces as $p) {
            $cities = self::city2($p->value);
            // $data = array_merge($data, $cities);
            foreach($cities as $c) {
                // $data[] = $c;
                array_push($data, $c);
                // $regions = self::city2($c->value);
                // print_r($regions);
                // if ($p->value == 4) {
                //     exit;
                // }
                // foreach ($regions as $r) {
                //     $data[] = $r;
                // }
             }
        }
        file_put_contents($file, json_encode($data, JSON_UNESCAPED_SLASHES));
    }
}
